#include "app_lora.h"

rt_thread_t thread_LoraRx;  //读环形缓冲区任务句柄
rt_sem_t    sem_LoraRx;     //读环形缓冲区信号量

sbuffer lora_rx_buff;


//写环形缓冲区
uint8_t sbuffer_write(uint8_t w, sbuffer* buf)
{
    int32_t i = (buf->wr + 1) % BUFFER_MAX;
    
    if(i != buf->rd)
    {
        buf->buffer[buf->wr] = w;
        buf->wr = i;
        return 1;
    }
    return 0;
    
}

//读环形缓冲区
uint8_t sbuffer_read(uint8_t* r, sbuffer* buf)
{
    if(buf->rd == buf->wr)
        return 0;
    else
    {
        *r = buf->buffer[buf->rd];
        buf->rd = (buf->rd + 1) % BUFFER_MAX;
        return 1;
    }
    
}

//写一个字节的环形缓冲区
uint8_t lora_buf_write_byte(uint8_t w)
{
    /* 写环形缓冲区 */
    if(sbuffer_write(w, &lora_rx_buff))
    {
        /* 释放信号量 */
        rt_sem_release(sem_LoraRx);
        return 1;
    }
    return 0;
}

//读一个字节的环形缓冲区
uint8_t lora_buf_read_byte(uint8_t* r, rt_int32_t time)
{
    /* 等待一个信号量 */
    rt_sem_take(sem_LoraRx, time);
    
    /* 返回读出的值 */
    return sbuffer_read(r, &lora_rx_buff);
}

//读环形缓冲区任务
void app_lora_rx_thread(void* parameter)
{
    uint8_t ch;
    while(1)
    {
        /* 读一个字节，读不到一直等 */
        lora_buf_read_byte(&ch, RT_WAITING_FOREVER);    
    }

}

//初始化Lora
void app_lora_init(void)
{
    /* 初始化缓冲区读写位置 */
    lora_rx_buff.rd = 0;
    lora_rx_buff.wr = 0;

    /* 创建信号量 */
    sem_LoraRx = rt_sem_create("sem_LoraRxSem",                 // 信号量名称
                                  0,                            // 初始值
                                  RT_IPC_FLAG_FIFO);            // 先进先出
    
    /* 创建读环形缓冲区任务 */
    thread_LoraRx = rt_thread_create("app_lora_rx_thread",      // 任务名称
                                       app_lora_rx_thread,      // 任务函数入口
                                       RT_NULL,                 // 参数
                                       512,                     // 栈大小
                                       5,                       // 优先级
                                       10);                     // 运行时间片
    
    /* 启动读环形缓冲区任务 */
    if(thread_LoraRx != NULL)
        rt_thread_startup(thread_LoraRx);
}
